package com.example.baseappstore.utils.net;

import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkHttpUtils {
    public static final String BASE_URL = "http://124.93.196.45:10001";

    private static final OkHttpClient ok = new OkHttpClient();

    public static String TOKEN = "";


    public static void doGet(String url, OkResult result) {
        Request request = new Request.Builder().url(BASE_URL + url)
                .addHeader(
                        "Authorization", TOKEN
                ).get().build();
        ok.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                result.onFailure(e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                handleResult(response, result);
            }
        });

    }


    public static void doPost(String url, Boolean hasToken, Map map,
                              OkResult result) {
        String s = CommonUtils.getGson().toJson(map);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), s);
        Request.Builder builder = new Request.Builder().url(BASE_URL + url)
                .addHeader(
                        "Authorization", TOKEN
                ).addHeader("Content-Type", "application/json").post(requestBody);
        Request request;
        if (hasToken == null) {
            request = builder.build();
        } else {
            request = builder.removeHeader("Authorization").build();
        }
        ok.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                result.onFailure(e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                handleResult(response, result);
            }
        });

    }


    public static void downloadFile(String url, File outputFile, OkResult result) {
        Request request = new Request.Builder().url(url).build();
        ok.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                result.onFailure(e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful() && response.body() != null) {
                    try (InputStream inputStream = response.body().byteStream();
                         FileOutputStream outputStream = new FileOutputStream(outputFile)
                    ) {
                        byte[] buffer = new byte[8 * 1024];// 8KB buffer size
                        int length = 0;
                        int downLoadLength = 0;
                        while ((length = inputStream.read(buffer)) != -1) {
                            outputStream.write(buffer, 0, length);
                            downLoadLength += length;
                            BigDecimal bigDecimal = BigDecimal.valueOf((float) downLoadLength / (1024 * 1024)).setScale(2,
                                    BigDecimal.ROUND_HALF_UP);
                            result.onSuccess(String.valueOf(bigDecimal));
                        }

                    } catch (IOException e) {
                        result.onFailure(e.getMessage());
                    }
                } else {
                    result.onFailure("Response not successful");
                }
            }
        });
    }
    
    private static void handleResult(Response response, OkResult result) {
        if (response.isSuccessful() && response.body() != null) {
            try {
                String string = response.body().string();
                JSONObject js = new JSONObject(string);
                if (js.optInt("code") == 200) {
                    result.onSuccess(string);
                } else {
                    result.onFailure(string);
                }
            } catch (Exception e) {
                e.printStackTrace();
                result.onFailure(e.getMessage());
            }
        } else {
            result.onFailure("请求出错," + response.code());
        }
    }

}
